import axios from "axios";
import NProgress from 'nprogress' // 引入nprogress插件
import 'nprogress/nprogress.css'
import { message } from "ant-design-vue";  // 这个nprogress样式必须引入
import router from '@/router/index.js'; // 从路由模块导入路由实例
import { useUser } from "@/store/index.js";
import {useAttrs} from "vue";

export const request = axios.create({
    baseURL: '/api',
    timeout: 60000
})

let loading = null
request.interceptors.request.use(function (config) {
    config.headers.saToken = localStorage.getItem('token') || '';
    // loading = showLoadingToast({
    //     message: '加载中...',
    //     forbidClick: true,
    //     duration: 0
    //   });
    NProgress.start() // 设置加载进度条(开始..)
    return config;
}, function (error) {
    NProgress.done() // 设置加载进度条(结束..)
    message.error("接口报错")
    return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(function (response) {
    if (response.data.data?.message?.includes("Token无效")) {
        message.warning("登录失效，请重新登录")
        //token过期直接清理登录数据
        localStorage.removeItem("token")
        localStorage.removeItem("user")
        const userStore = useUser()
        userStore.clearInfo()
        router.push("/login")
    }
    NProgress.done() // 设置加载进度条(结束..)
    return Promise.resolve(response.data);
}, function (error) {
    NProgress.done() // 设置加载进度条(结束..)
    return Promise.reject(error);
});

export const methodType = {
    get: 'GET',
    post: 'POST',
    delete: 'DELETE',
    put: 'PUT'
}
